package com.zmn.plat.business.impl.warranty.content;

import java.util.*;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.plat.business.interfaces.warranty.content.WarrantyContentBService;
import com.zmn.plat.model.entity.warranty.info.WarrantyInfo;
import com.zmn.plat.model.entity.warranty.info.WarrantyInfoQuery;
import com.zmn.plat.services.interfaces.warranty.content.WarrantyContentService;
import com.zmn.plat.services.interfaces.warranty.info.WarrantyInfoService;

@Service
public class WarrantyContentBServiceImpl implements WarrantyContentBService {

    @Resource
    WarrantyInfoService warrantyInfoService;
    @Resource
    WarrantyContentService warrantyContentService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatusBatchAndDeleteWarrantyInfoByKey(List<Integer> ids, Integer status, String mcStaffName) {
        if (Objects.equals(GlobalConsts.NO, status)) {
            warrantyContentService.updateStatusBatchByKey(ids, status, mcStaffName);

            WarrantyInfoQuery warrantyInfoQuery = new WarrantyInfoQuery();
            warrantyInfoQuery.setWarrantyContentIds(ids);
            List<WarrantyInfo> warrantyInfos = warrantyInfoService.listByQuery(warrantyInfoQuery);
            List<Integer> deleteKeys = new ArrayList<>();
            List<WarrantyInfo> updateWarrantyInfos = new ArrayList<>();
            for (int i = 0; i < warrantyInfos.size(); i++) {
                WarrantyInfo warrantyInfo = warrantyInfos.get(i);
                boolean isDelete = judgeAndHandleWarrantyInfo(warrantyInfo, ids, mcStaffName);
                if (isDelete) {
                    deleteKeys.add(warrantyInfo.getWarrantyInfoId());
                } else {
                    updateWarrantyInfos.add(warrantyInfo);
                }
            }

            if (CollectionUtil.isNotNullOrEmpty(deleteKeys)) {
                warrantyInfoService.deleteByKeys(deleteKeys);
            }

            if (CollectionUtil.isNotNullOrEmpty(updateWarrantyInfos)) {
                warrantyInfoService.updateBatch(updateWarrantyInfos);
            }

        } else if (Objects.equals(GlobalConsts.YES, status)) {
            warrantyContentService.updateStatusBatchByKey(ids, status, mcStaffName);
        }
    }

    /**
     * 根据保修信息和保修内容IDS判断是否删除该条数据或者更新保修信息数据
     * 
     * @param warrantyInfo
     * @param warrantyContentIds
     * @param mcStaffName
     * @return true 表示需要删除的数据 false表示需要更新的数据
     */
    private boolean judgeAndHandleWarrantyInfo(WarrantyInfo warrantyInfo, List<Integer> warrantyContentIds, String mcStaffName) {
        String warrantyContentIdStr = warrantyInfo.getWarrantyContentIdStr();
        warrantyContentIdStr = trimBothEndsChars(warrantyContentIdStr, "\\$");
        List<Integer> realWarrantyContentIds = Arrays.stream(warrantyContentIdStr.split("\\$")).map(e -> Integer.parseInt(e)).collect(Collectors.toList());

        // 如果停用的保修内容IDS和保修信息中包含的保修内容IDS完全吻合，则删除该条保修信息，否则则更新
        boolean flag = compare(realWarrantyContentIds, warrantyContentIds);
        if (flag) {
            return true;
        } else {
            realWarrantyContentIds.removeAll(warrantyContentIds);
            if (CollectionUtil.isNullOrEmpty(realWarrantyContentIds)) {
                return true;
            }
            String result = realWarrantyContentIds.stream().map(e -> String.valueOf(e)).collect(Collectors.joining("$", "$", "$"));
            warrantyInfo.setWarrantyContentIdStr(result);
            warrantyInfo.setUpdater(mcStaffName);
            warrantyInfo.setUpdateTime(DateUtil.getNow());
        }

        return false;
    }

    private String trimBothEndsChars(String srcStr, String splitter) {
        String regex = "^" + splitter + "*|" + splitter + "*$";
        return srcStr.replaceAll(regex, "");
    }

    public static <T extends Comparable<T>> boolean compare(List<T> a, List<T> b) {
        if (a.size() != b.size()) {
            return false;
        }

        Collections.sort(a);
        Collections.sort(b);

        for (int i = 0; i < a.size(); i++) {
            if (!a.get(i).equals(b.get(i))) {
                return false;
            }
        }

        return true;
    }
}
